package com.dapeis.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.ag.dao.DBService;
import com.ag.dao.IDao;
import com.dapeis.core.utils.DBConfigUtils;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.dao.ICollocationPlanMapper;
import com.dapeis.dao.IPlanAgreeLogMapper;
import com.dapeis.domain.Plan;
import com.dapeis.domain.PlanAgreeLog;
import com.dapeis.exception.plan.UserExitsAgreeException;

@Service
public class CollocationPlanService extends DBService<Plan> {
    @Resource
    ICollocationPlanMapper mapper;

    @Resource
    IPlanAgreeLogMapper agreeLogMapper;

    @Override
    protected IDao<Plan> getIDao() {
	return mapper;
    }

    /**
     * 点赞
     * 
     * @param plan
     * @param userId
     * @return
     */
    public boolean doAgree(Plan plan, Integer userId) {
	if (!isExitAgree(plan, userId)) {
	    plan.setAgreeNum(plan.getAgreeNum() + 1);
	    PlanAgreeLog log = new PlanAgreeLog();
	    agreeLogMapper.insertSelective(log.buildPlanAgreeLog(userId,
		    plan.getId()));
	    return mapper.updateByPrimaryKeySelective(plan) > 0;
	}
	throw new UserExitsAgreeException();
    }

    /**
     * 检查该用户是否已点赞该方案 true 已点赞 false 未点赞
     * 
     * @param plan
     * @param userId
     * @return
     */
    public boolean isExitAgree(Plan plan, Integer userId) {
	Example example = new Example(PlanAgreeLog.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(PlanAgreeLog.PROPERTY_USERID, userId);
	criteria.andEqualTo(PlanAgreeLog.PROPERYT_PLANID, plan.getId());
	return agreeLogMapper.selectCountByExample(example) > 0;
    }

    /**
     * 获取搭配方案,暂定15条
     * @param collocationId
     * @return
     */
    public List<String> getPlanImgList(Integer collocationId) {
	Example example = new Example(Plan.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(Plan.PROPERTY_COLLOCATIONID, collocationId);
	criteria.andEqualTo(Plan.PROPERTY_ISSUE,
		StylistConstants.PlanState.ISSUE);
	example.orderBy(Plan.PROPERTY_CREATETIME).desc();
	List planList = selectByExampleAndRowBounds(example, new RowBounds(0,
		15));
	List<String> planImgList = new ArrayList<String>();
	if (!planList.isEmpty()) {
	    for (Iterator iterator = planList.iterator(); iterator.hasNext();) {
		Plan plan = (Plan) iterator.next();
		if (null != plan) {
		    planImgList.add(DBConfigUtils.getFullImgPath(plan
			    .getMasterImage()));
		}
	    }
	}
	return planImgList;
    }

}
